<?php


namespace App\Services\Repo;

use App\Models\Company;
use App\Models\Group;
use App\Models\Project;
use App\Models\User;
use App\Services\Interfaces\RepoServiceInterface;
use Illuminate\Database\Eloquent\Model;
use Auth;
use League\Flysystem\Exception;

class GroupRepo implements RepoServiceInterface
{
    /**
     * 创建组织架构
     */
    public function create(array $_options = null):Model
    {
        $group = new Group();
        $group->name = $_options['name'];
        $group->children = [];
        $group->parent_id = $_options['parent_id'];
        $pGroup = Group::find($_options['parent_id']);//如果能找到上一级的内容，当前的company就是上一级的company，同事要把当前group的ID放入上一级的children
        if (!empty($pGroup)) {
            $group->company_id = $pGroup->company_id;
            $group->save();
            $children = Group::find($group->parent_id);
            if (!empty($children)) {
                $arr_children = $children->children;
            } else {
                $arr_children = [];
            }
            array_push($arr_children, $group->_id);
            Group::where('_id', $group->parent_id)->update(['children' => $arr_children]);
        }
        return $group;
    }

    /**
     * 组织架构列表
     */

    public function read($limit = 0)
    {
        $user = request()->user();//相当于Auth::user()

        assert($user->company, "找不到用户【{$user->name}】对应的company,");//断言，当前面条件为false的时候执行后面的语句
        /**@var Group $group * */
        $group = $user->group;
        if (!is_null($group)) {
            $groups = $group->genTreeBy();//获取所有子结构数据
        } else {
            // group 为空, 检查当前用户是否是超级管理员,如果是的话,把当前渠道所有group返回
            $role = $user->role ?? null;//新的三元运算，前面条件为真的话就取前面的，否则取？右边的
            if (!is_null($role) && $role->actions === []) {//档actions为空的时候表示该角色是超级管理员
                $groups = Group::companyTree($user->company->id);//获取所有子数据
            } else {
                $groups = new \stdClass;//生成一个空对象
            }
        }
        return $groups;
    }

    /**
     * 组织架构详情
     */

    public function find(array $_filter):Model
    {
        $res = Group::find($_filter)->first();
        return $res;
    }

    public function update(array $_filter, array $_update_data):bool
    {
        $group = Group::find($_filter)->first();//先获取要修改的原来的数据
        $group_id = $group->_id;
        $pro_id = Project::where('group_id', $group_id)//找到相关绑定项目的ID
        ->get()
            ->pluck('_id')
            ->all();
        if (!is_null($group)) {
            if ($group->name == $_update_data['name']) {//如果修改名称与当前名称相同则不能修改
                return true;
            }
            $group->name = $_update_data['name'];
            // 修改最下级组织, 得把项目名称也改了
            if (!empty($pro_id)) {
                $project = Project::find($pro_id)->first();
                $project->title = $_update_data['name'];
                $project->save();
            }
            return $group->save();
        } else {
            return false;
        }
    }

    /**
     * 删除组织架构
     */
    public function delete(array $_filter):bool
    {
        $group = Group::find($_filter)->first();
        $pId = $group->parent_id;
        if (!empty($pId)) {
            $pGroup = Group::find($pId);
            $children = $pGroup->children;
            $k = array_search($_filter['id'], $children);
            if ($k !== false) {
                unset($children[$k]);//去除父级的children
            }
            $pGroup->children = array_values($children);
            $pGroup->save();
            $project_ids = Project::where('group_id', $_filter['id'])
                ->get()
                ->pluck('_id')
                ->all();
            if (!empty($project_ids)) {
                Project::destroy($project_ids);//删除绑定的项目
            }

        }
        return Group::destroy($_filter);
    }
}
